<template>
  <div class="app-container customer-div">
    <el-menu :default-active="listQuery1.tab" class="el-menu-demo" mode="horizontal" @select="handleSelect">
      <el-menu-item index="my">我的</el-menu-item>
      <el-menu-item index="department" v-if="saleWorkOrderForDepartment">部门</el-menu-item>
      <el-menu-item index="all" v-if="saleWorkOrderForAll">全部</el-menu-item>
    </el-menu>

    <div style="margin-top:40px">
      <el-form :inline="true" :model="listQuery1" size="mini" label-width="100px">

        <el-form-item label="客户名称：">
          <el-select
            v-model="listQuery1.customerId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入关键词"
            :remote-method="remoteMethod1"
            :loading="customerLoading">
            <el-option
              v-for="item in customerList"
              :key="item.customerId"
              :label="item.customerName"
              :value="item.customerId">
            </el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="业务员：" v-if="listQuery1.tab !='my'">
          <el-select v-model="listQuery1.userId" filterable placeholder="请选择" clearable>
            <el-option
              v-for="item in userOptionList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="开始时间：">
          <el-date-picker
            v-model="listQuery1.startDate"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="结束时间：">
          <el-date-picker
            v-model="listQuery1.endDate"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="实际完成时间：">
          <el-date-picker
            v-model="listQuery1.replyDate"
            type="daterange"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="发布人：">
          <el-select v-model="listQuery1.createUserId" filterable placeholder="请选择" clearable>
            <el-option
              v-for="item in userOptionList"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="工单状态：">
          <el-select v-model="listQuery1.woState" placeholder="请选择" clearable>
            <el-option label="待处理" :value="0"></el-option>
            <el-option label="已处理" :value="10"></el-option>
            <el-option label="已作废" :value="20"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="发起页：">
          <el-select v-model="listQuery1.woSource" placeholder="请选择" clearable>
            <el-option label="客户详情" value="customerId"></el-option>
            <el-option label="跟进详情" value="trackingId"></el-option>
            <el-option label="其它" value="customerList"></el-option>
            <el-option label="客户应收款" value="customerNeedPay"></el-option>

          </el-select>
        </el-form-item>


        <el-form-item>
          <el-button
            @click="handleSearchList1()"
            type="primary">
            查询
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <!--数据列表-->
    <div class="table-container">
      <el-table
        v-loading="listLoading1"
        :data="tableData1"
        max-height="460"
        border
        style="width: 100%; margin-top: 20px">
        <el-table-column  label="客户名称" min-width="200" align="center" header-align="center">
          <template slot-scope="scope">
                {{scope.row.customerName}}
          </template>
        </el-table-column>
        <el-table-column
          label="销售员"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.userName}}
          </template>
        </el-table-column>
        <el-table-column
          label="开始时间"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.startDate}}
          </template>
        </el-table-column>
        <el-table-column
          label="结束时间"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.endDate}}
          </template>
        </el-table-column>
        <el-table-column
          label="发布人"
          min-width="100"
          align="center">
          <template slot-scope="scope">
            {{scope.row.createUserName}}
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          label="工单内容"
          min-width="200">
          <template slot-scope="scope">
            {{scope.row.woContent}}
          </template>
        </el-table-column>
        <el-table-column
          header-align="center"
          label="反馈内容"
          min-width="200">
          <template slot-scope="scope">
            {{scope.row.replyContent}}
          </template>
        </el-table-column>
        <el-table-column
          label="完成时间"
          align="center"
          min-width="120">
          <template slot-scope="scope">
            {{scope.row.replyDate}}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="工单状态"
          min-width="100">
          <template slot-scope="scope">
            {{scope.row.woState | fifstate}}
          </template>
        </el-table-column>
        <el-table-column
          label="是否需反馈"
          align="center"
          min-width="100">
          <template slot-scope="scope">
            {{scope.row.isNeedReply}}
          </template>
        </el-table-column>
        <el-table-column
          label="发起页面"
          align="center"
          min-width="100">
          <template slot-scope="scope">
            {{scope.row.woSource | fifwoSource}}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          fixed="right"
          align="center"
          min-width="150">
          <template slot-scope="scope">
            <el-button
              v-if="listQuery1.tab == 'my' && scope.row.woState == 0"
              type="text"
              @click="feedback(scope.row)"
              size="mini">反馈
            </el-button>
            <el-button
              v-if="listQuery1.tab != 'my' && scope.row.woState != 20"
              type="text"
              @click="setCancel(scope.row)"
              size="mini">作废
            </el-button>
            <el-button
              @click="toPage(scope.row)"
              type="text"
              size="mini">
                查看关联页面
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange1"
        @current-change="handleCurrentChange1"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery1.pageNum"
        :page-size="listQuery1.pageSize"
        :page-sizes="[10,15,20]"
        :total="count1">
      </el-pagination>
    </div>

    <el-dialog
      :close-on-click-modal="false"
      :beforeClose="handleClose"
      title="反馈"
      :visible.sync="dialogVisible"
      width="500px">
      <el-form :model="form" size="mini" label-width="100px"  ref="form" :rules="rules">

        <el-form-item label="反馈内容" prop="replyContent">
          <el-input :autosize="{ minRows: 2, maxRows: 6}" type="textarea" v-model.trim="form.replyContent"></el-input>
        </el-form-item>

      </el-form>
      <span slot="footer" class="dialog-footer">
            <el-button @click="handleClose">取 消</el-button>
            <el-button type="primary" @click="handleConfirm" :loading="btnLoading">确 定</el-button>
        </span>
    </el-dialog>

  </div>
</template>
<script>

import {getOrderUsersList,getCustomerOption} from '@/api/partner'
import {workOrderList,workOrderOperate} from '@/api/fms.js'
import store from '@/store'
import { mapGetters } from 'vuex'

const defaultListQuery={
  "tab" : "my", //我的-my,部门-department，全部-all
  "date" : [],  //下单时间
  "userId" : '',  //业务员
  "customerId" : '',//客户ID
  "woState" : '', //工单状态（0待回复、10已回复、20已作废）
  "startDate" : [],//开始日期
  "endDate" : [],//结束日期
  "replyDate" : [],//实际完成时间
  "createUserId" : '', //工单发布人
  woSource:'',
  "pageNum" : 1,
  "pageSize" : 10
};

const defaultForm={
  "woId" : 1,
  "action" : "reply", //操作类型(回复：reply，作废：cancel)
  "replyContent" : "",
}

export default {
  name: "index",
  data(){
    return {
      roles:store.getters.roles ? store.getters.roles : [],
      listQuery1: JSON.parse(JSON.stringify(defaultListQuery)),
      tableData1: [],
      count1: 0,
      listLoading1: false,
      userOptionList:[],
      form:JSON.parse(JSON.stringify(defaultForm)),
      dialogVisible:false,
      btnLoading:false,
      rules:{
        replyContent:[{required: true, trigger: 'blur' ,message: '此项必填',}],
      },
      customerList:[],
      customerLoading:false,
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'mobile',
      'userId'
    ]),
    saleWorkOrderForAll (){
      if(this.roles.indexOf("saleWorkOrderForAll") != -1){
        return true
      }else{
        return false
      }
    },
    saleWorkOrderForDepartment (){
      if(this.roles.indexOf("saleWorkOrderForDepartment") != -1){
        return true
      }else{
        return false
      }
    },
  },
  created() {
    this.getUserOptionList();
    this.getList1();
  },
  filters: {
    fifstate(val){
      if(val == 0){
        return '待处理'
      }else if(val == 10){
        return '已处理'
      }else if(val == 20){
        return '已作废'
      }
    },
    fifwoSource(val){
      if(val == 'customerId'){
        return '客户详情'
      }else if(val == 'trackingId'){
        return '跟进详情'
      }else if(val == 'customerList'){
        return '其它'
      }else if(val == 'customerNeedPay'){
        return '客户应收款'
      }
    }

  },
  methods:{
    //获取客户列表
    remoteMethod1(query) {
      if(query && query!= ''){
        this.customerLoading = true;
        getCustomerOption({keywords:query}).then(response => {
          this.customerList = response;
          this.customerLoading = false;
        }).catch(()=>{
          this.customerLoading = false;
        });
      }
    },
    toPage(item){
      let routeData = this.$router.resolve({name:'customerDetail',query:{id:item.customerId}});
      if(item.woSource == 'trackingId'){
        let tab = this.listQuery1.tab == 'my' ? '1' : this.listQuery1.tab == 'department' ? '2' : '0'
        routeData = this.$router.resolve({name:'followDetailsList',query:{tab:tab,trackingId:item.trackingId}});
      }else if(item.woSource == 'customerNeedPay'){
        routeData = this.$router.resolve({name:'customerReceivables',query:{tab:this.listQuery1.tab,orderSn:item.orderSn}});
      }
      window.open(routeData.href);
    },
    handleClose(){
      this.dialogVisible = false;
    },
    handleConfirm(){
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.btnLoading = true;
          let data = JSON.parse(JSON.stringify(this.form));
          workOrderOperate(data).then(response => {
            this.btnLoading = false;
            this.$message({
              message: '提交成功',
              type: 'success',
              duration: 1000
            });
            this.handleClose();
            this.getList1()
          }).catch(() => {
            this.btnLoading = false;
          })
        }
      })
    },
    //反馈
    feedback(item){
      this.dialogVisible = true
      this.form = JSON.parse(JSON.stringify(defaultForm))
      this.form.woId = item.woId
    },
    setCancel(item){
      this.$confirm('确定要作废吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        workOrderOperate({woId:item.woId,action:'cancel'}).then(()=>{
          this.$message({
            type: 'success',
            message: '作废成功!'
          });
          this.getList1()
        })

      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消作废'
        });
      });
    },
    handleSelect(key){
      this.listQuery1 = JSON.parse(JSON.stringify(defaultListQuery))
      this.listQuery1.tab = key
      this.handleSearchList1()
    },

    //获取列表
    getList1(){
      this.listLoading1 = true;
      let listQuery = JSON.parse(JSON.stringify(this.listQuery1));
      workOrderList(listQuery).then(response => {
        this.tableData1 = response.list;
        this.count1 = response.count;
        this.listLoading1 = false;
      }).catch(()=>{
        this.listLoading1 = false;
      });
    },

    handleSizeChange1(val){
      this.listQuery1.pageNum = 1;
      this.listQuery1.pageSize = val;
      this.getList1();
    },
    handleCurrentChange1(val){
      this.listQuery1.pageNum = val;
      this.getList1();
    },

    handleSearchList1(){
      this.listQuery1.pageNum = 1;
      this.getList1();
    },

    //获取员工下拉选项
    getUserOptionList(){
      getOrderUsersList({type:'sale'}).then((res)=>{
        this.userOptionList = res;
      })
    },



  },
}
</script>

<style scoped lang="scss">
.upload-div{
  text-align: center;
  position:relative;
  #upload{

    opacity: 0;
    position: absolute;
    z-index: 1;
    width:154px;
    height:40px
  }
}
.title-tab{
  border-radius: 8px;
  background: #eee;
  margin-left: 10px;
  display: inline-block;
  vertical-align: middle;
  line-height: 20px;
  padding: 0 5px;
  color: #666;
}
</style>
